import 'dart:math';

import 'package:flutter/material.dart';

class FutureBuilderPage extends StatefulWidget {
  @override
  _FutureBuilderPageState createState() => _FutureBuilderPageState();
}

class _FutureBuilderPageState extends State<FutureBuilderPage> {
  int _retryCount = 0;
  Future<String>? _future;

  Future<String> mockNetworkData() async {
    // 模拟网络请求延迟
    await Future.delayed(Duration(seconds: 3));
    // 前两次请求失败，第三次成功
    if (_retryCount < 2) {
      _retryCount++;
      throw Exception("网络请求失败，重试次数: $_retryCount");
    } else {
      return "我是从互联网上获取的数据";
    }
  }

  void _retry() {
    setState(() {
      _future = mockNetworkData();
    });
  }

  @override
  void initState() {
    super.initState();
    _future = mockNetworkData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('FutureBuilder Demo')),
      body: Center(
        child: FutureBuilder<String>(
          future: _future,
          builder: (context, snapshot) {
            // 请求未结束，显示loading
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('请求中...'),
                ],
              );
            } else if (snapshot.hasError) {
              // 请求失败，显示错误和重试按钮
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Error: ${snapshot.error}'),
                  SizedBox(height: 16),
                  ElevatedButton(onPressed: _retry, child: Text('重试')),
                ],
              );
            } else {
              // 请求成功，显示数据
              return Text('${snapshot.data}');
            }
          },
        ),
      ),
    );
  }
}
